﻿using System;
using System.Diagnostics;
using System.Threading;

namespace AdbRegisterUtils
{
    public static class AdbLogcatManager
    {
        private static CmdTerminalService _logcatTerminalService;
        private static bool _isInitialized = false;
        private static readonly object _lockObject = new object();

        /// <summary>
        /// 初始化Logcat数据采集器
        /// </summary>
        public static void Initialize()
        {
            lock (_lockObject)
            {
                try
                {
                    if (_isInitialized)
                    {
                        Console.WriteLine("Logcat数据采集器已初始化");
                        return;
                    }

                    // 使用 ProcessStartInfoManager 创建配置
                    var startInfo = ProcessStartInfoManager.GetDefaultCmdStartInfo();

                    // 初始化 logcat 终端服务，专注于数据处理
                    _logcatTerminalService = new CmdTerminalService(OnLogcatOutput, startInfo);
                    _isInitialized = true;

                    Console.WriteLine("Logcat数据采集器已初始化");
                }
                catch (Exception ex)
                {
                    throw new Exception($"初始化Logcat数据采集器失败: {ex.Message}", ex);
                }
            }
        }

        /// <summary>
        /// Logcat输出处理 - 专注于数据采集和存储
        /// </summary>
        private static void OnLogcatOutput(string commandType, string output)
        {
            if (string.IsNullOrEmpty(output)) return;

            try
            {
                // 添加输出打印
                Console.WriteLine($"[OnLogcatOutput] 接收到输出: {output}");

                // 过滤终端启动消息和清空命令的响应
                if (output.Contains("CMD 终端已启动") ||
                    output.Contains("CMD terminal started") ||
                    output.Contains("logcat -c") ||
                    output.Contains("clear") ||
                    string.IsNullOrWhiteSpace(output))
                    return;

                // 直接调用 LogcatDataManager 解析和存储
                LogcatDataManager.ParseAndStoreRegisterLog(output);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"[ERROR] 处理logcat输出时发生错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空初始缓冲区，跳过启动时的无用信息
        /// </summary>
        private static void ClearInitialBuffer()
        {
            try
            {
                if (!_isInitialized || _logcatTerminalService == null)
                {
                    Console.WriteLine("Logcat数据采集器未初始化，无法清空缓冲区");
                    return;
                }

                Console.WriteLine("开始清空初始缓冲区...");

                // 等待终端稳定
                Thread.Sleep(500);

                // 清空任何可能存在的初始输出
                _logcatTerminalService.ClearOutputBuffer();

                Console.WriteLine("初始缓冲区已清空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空初始缓冲区时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 启动logcat数据采集（使用xmh过滤）
        /// </summary>
        public static bool StartLogcat()
        {
            lock (_lockObject)
            {
                try
                {
                    if (!_isInitialized)
                    {
                        Console.WriteLine("Logcat数据采集器未初始化，正在自动初始化...");
                        Initialize();
                    }

                    if (_logcatTerminalService == null)
                    {
                        Console.WriteLine("Logcat终端服务未初始化");
                        return false;
                    }

                    // 先停止当前终端中的命令（如果有）
                    StopCurrentLogcat();

                    // 清空logcat缓冲区
                    ClearLogcat();

                    // 清空初始缓冲区
                    ClearInitialBuffer();

                    // 发送过滤命令
                    string logcatCmd = "adb shell logcat | findstr \"xmh\"";
                    _logcatTerminalService.SendCommand(logcatCmd);

                    Console.WriteLine("Logcat数据采集已启动（使用xmh过滤）");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"启动logcat数据采集失败: {ex.Message}");
                    return false;
                }
            }
        }

        /// <summary>
        /// 启动完整logcat数据采集（不过滤）
        /// </summary>
        public static bool StartFullLogcat()
        {
            lock (_lockObject)
            {
                try
                {
                    if (!_isInitialized)
                    {
                        Console.WriteLine("Logcat数据采集器未初始化，正在自动初始化...");
                        Initialize();
                    }

                    if (_logcatTerminalService == null)
                    {
                        Console.WriteLine("Logcat终端服务未初始化");
                        return false;
                    }

                    // 先停止当前终端中的命令（如果有）
                    StopCurrentLogcat();

                    // 清空logcat缓冲区
                    ClearLogcat();

                    // 清空初始缓冲区
                    ClearInitialBuffer();

                    // 启动完整的logcat命令
                    string logcatCmd = "adb shell logcat";
                    _logcatTerminalService.SendCommand(logcatCmd);

                    Console.WriteLine("Logcat数据采集已启动（完整日志）");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"启动完整logcat数据采集失败: {ex.Message}");
                    return false;
                }
            }
        }

        /// <summary>
        /// 启动logcat数据采集（带缓冲区清理和初始延迟）
        /// </summary>
        public static bool StartLogcatWithCleanBuffer()
        {
            return StartLogcatInternal(false);
        }

        /// <summary>
        /// 启动完整logcat数据采集（带缓冲区清理和初始延迟）
        /// </summary>
        public static bool StartFullLogcatWithCleanBuffer()
        {
            return StartLogcatInternal(true);
        }

        /// <summary>
        /// 内部启动方法
        /// </summary>
        private static bool StartLogcatInternal(bool fullLogcat)
        {
            lock (_lockObject)
            {
                try
                {
                    if (!_isInitialized)
                    {
                        Initialize();
                    }

                    if (_logcatTerminalService == null)
                    {
                        return false;
                    }

                    // 停止当前命令
                    StopCurrentLogcat();

                    // 步骤1: 清空设备上的logcat缓冲区
                    ExecuteIndependentClearCommand();

                    // 步骤2: 清空终端服务的输出缓冲区
                    _logcatTerminalService.ClearOutputBuffer();

                    // 步骤3: 等待系统稳定
                    Thread.Sleep(300);

                    // 步骤4: 发送logcat命令
                    string logcatCmd = fullLogcat ?
                        "adb shell logcat" :
                        "adb shell logcat | findstr \"xmh\"";

                    _logcatTerminalService.SendCommand(logcatCmd);

                    // 步骤5: 跳过初始的无用输出
                    SkipInitialOutput(1000);

                    Console.WriteLine($"Logcat数据采集已启动{(fullLogcat ? "（完整日志）" : "（使用xmh过滤）")}");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"启动logcat数据采集失败: {ex.Message}");
                    return false;
                }
            }
        }

        /// <summary>
        /// 执行独立的清空命令
        /// </summary>
        private static void ExecuteIndependentClearCommand()
        {
            try
            {
                using (Process clearProcess = new Process())
                {
                    var startInfo = ProcessStartInfoManager.GetDefaultCmdStartInfo();
                    clearProcess.StartInfo = startInfo;

                    clearProcess.Start();

                    // 发送清空命令
                    clearProcess.StandardInput.WriteLine("adb logcat -c");
                    clearProcess.StandardInput.Flush();

                    Thread.Sleep(200); // 等待命令执行

                    clearProcess.StandardInput.WriteLine("exit");

                    if (!clearProcess.WaitForExit(1000))
                    {
                        clearProcess.Kill();
                    }
                }

                Console.WriteLine("已执行独立清空命令");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行独立清空命令失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 跳过初始输出
        /// </summary>
        private static void SkipInitialOutput(int delayMs)
        {
            try
            {
                Console.WriteLine("跳过初始输出...");
                Thread.Sleep(delayMs);
                _logcatTerminalService.ClearOutputBuffer();
                Console.WriteLine("初始输出已跳过");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"跳过初始输出时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止当前终端中的logcat命令
        /// </summary>
        public static bool StopCurrentLogcat()
        {
            lock (_lockObject)
            {
                try
                {
                    if (!_isInitialized || _logcatTerminalService == null)
                    {
                        Console.WriteLine("Logcat数据采集器未初始化或未运行");
                        return true;
                    }

                    // 发送Ctrl+C停止当前终端中的命令
                    _logcatTerminalService.SendCommand("\x3");
                    Thread.Sleep(200); // 短暂等待命令停止

                    // 清空输出缓冲区
                    _logcatTerminalService.ClearOutputBuffer();

                    Console.WriteLine("已停止当前终端中的logcat命令");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"停止当前logcat命令失败: {ex.Message}");
                    return false;
                }
            }
        }

        /// <summary>
        /// 清除logcat缓冲区
        /// </summary>
        public static bool ClearLogcat()
        {
            lock (_lockObject)
            {
                try
                {
                    if (!_isInitialized || _logcatTerminalService == null)
                    {
                        Console.WriteLine("Logcat数据采集器未初始化");
                        return false;
                    }

                    // 发送清除缓冲区的命令
                    string clearCmd = "adb logcat -c";
                    _logcatTerminalService.SendCommand(clearCmd);

                    Thread.Sleep(200); // 等待清空完成

                    Console.WriteLine("已发送清除logcat缓冲区命令");
                    return true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"清除logcat缓冲区失败: {ex.Message}");
                    return false;
                }
            }
        }

        /// <summary>
        /// 完全重置logcat采集器
        /// </summary>
        public static void ResetLogcat()
        {
            lock (_lockObject)
            {
                try
                {
                    Console.WriteLine("开始重置Logcat采集器...");

                    // 停止当前命令
                    StopCurrentLogcat();

                    // 清空缓冲区
                    ClearLogcat();

                    // 清空终端输出缓冲区
                    _logcatTerminalService?.ClearOutputBuffer();

                    // 等待重置完成
                    Thread.Sleep(300);

                    Console.WriteLine("Logcat采集器重置完成");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"重置Logcat采集器失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 获取采集状态
        /// </summary>
        public static bool IsLogcatRunning => _isInitialized && _logcatTerminalService != null;

        /// <summary>
        /// 清理资源
        /// </summary>
        public static void Cleanup()
        {
            lock (_lockObject)
            {
                try
                {
                    StopCurrentLogcat();
                    _logcatTerminalService?.Dispose();
                    _logcatTerminalService = null;
                    _isInitialized = false;
                    Console.WriteLine("Logcat数据采集器已清理");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"清理Logcat数据采集器时发生错误: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 获取终端服务实例（用于调试）
        /// </summary>
        public static CmdTerminalService GetLogcatTerminalService()
        {
            return _logcatTerminalService;
        }
    }
}